/*
 * Copyright (c) 2015 smarthome.com All rights reserved. 本软件源代码版权归----所有,未经许可不得任意复制与传播.
 */
package com.smarthome.web.property.controller.kuaidiXiyi;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smarthome.common.tools.excel.ReportExportService;
import com.smarthome.core.historyAccount.HistoryAccountService;
import com.smarthome.core.kuaidiXiyi.XiyiOrderService;
import com.smarthome.core.message.util.MessageUtil;
import com.smarthome.core.operationservicemanager.CompanyLaundryService;
import com.smarthome.domain.bean.ShCompanyLaundry;
import com.smarthome.domain.bean.ShHistoryAccount;
import com.smarthome.domain.bean.ShOrders;
import com.smarthome.domain.common.Result;
import com.smarthome.domain.enums.SmsTypeEnum;
import com.smarthome.domain.vo.boss.DataGrid;
import com.smarthome.domain.vo.boss.PageHelper;
import com.smarthome.web.property.utils.UserHolder;

/**
 * 洗衣服务 controller层
 * 
 * 
 */
@Controller
@RequestMapping("/xiyiOrderController")
public class XiyiOrderServerController {

    @Resource
    private XiyiOrderService xiyiOrderService;

    @Resource
    private HistoryAccountService historyAccountService;
    
    @Resource
    private CompanyLaundryService companyLaundryService;
    
    
    /**
     * 获取洗衣工单信息列表--翻页
     * @param accountLog
     * @param page
     * @return
     */
    @RequestMapping("/dataGrid")
    @ResponseBody
    public DataGrid dataGrid(HttpServletRequest request,ShOrders shOrders, PageHelper page) {
    	String ordStatus = request.getParameter("ordStatus");		//订单状态
    	String phone = request.getParameter("phone");	//客户电话
    	
    	if(!UserHolder.isSuperResidence()){
    		Long residenceId = UserHolder.getCurrentResidenceId();
        	shOrders.setResidenceId(residenceId);
    	}
    	if(StringUtils.isNotBlank(ordStatus)){
    		shOrders.setStatus(Integer.valueOf(ordStatus));
    	}
    	if(StringUtils.isNotBlank(phone)){
    		shOrders.setSrcMobile(phone);
    	}
    	shOrders.setOrderType(3);
        return xiyiOrderService.dataGrid(shOrders, page);
    }

    /**
     * 跳转到添加页面
     * 
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(HttpServletRequest request) {
    	Long residenceId = UserHolder.getCurrentResidenceId();
    	request.setAttribute("residenceId", residenceId);
        return "/kuaidiXiyi/xiyiServerAdd";
    }

    /**
     * 新增洗衣服务订单
     * @param deviceSupplier
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Result add(HttpServletRequest request,ShOrders shOrders) {
        try {
        	String phone = request.getParameter("phone");		//手机号码
        	String kh_name = request.getParameter("kh_name");	//手机号码
        	if(StringUtils.isBlank(phone)){
        		 return Result.failure("请输入手机号码！");
        	}
        	//通过手机号码查询用户是否存在
        	Long srcAccountId =0l;
        	ShHistoryAccount shHistoryAccount = new ShHistoryAccount();
        	shHistoryAccount.setMobile(phone);
        	List<ShHistoryAccount> list = historyAccountService.queryShHistoryAccountList(shHistoryAccount);
        	if(list!=null && list.size()>0){
        		srcAccountId=list.get(0).getId();
        	}else{									//新增
        		if(StringUtils.isNotBlank(kh_name)){
        			shHistoryAccount.setName(kh_name);
        		}
        		shHistoryAccount.setStatus(1);				//是否可用,1可用,2不可用
        		shHistoryAccount.setGmtCreate(new Date());	//创建时间
        		historyAccountService.add(shHistoryAccount);
        		//再查一边，得到id
        		List<ShHistoryAccount> list2 = historyAccountService.queryShHistoryAccountList(shHistoryAccount);
            	if(list2!=null && list2.size()>0){
            		srcAccountId=list2.get(0).getId();
            	}
        	}
        	
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        	String orderNum= sdf.format(new Date());
        	Long residenceId = UserHolder.getCurrentResidenceId();
        	int num=(int)(Math.random()*900)+100; 
        	//int i= new java.util.Random().nextInt(900)+100;也可以
        	shOrders.setId(Long.valueOf(orderNum+num));//订单号
        	shOrders.setResidenceId(residenceId);
        	shOrders.setSrcAccountId(srcAccountId);
        	shOrders.setGmtCreate(new Date());
        	shOrders.setStatus(1);//订单状态,1待处理
        	shOrders.setOrderType(3);//订单类型,1收快递,2发快递,3洗衣
        	
        	String amountStr = request.getParameter("amountStr");	//手机号码
        	Long amount=0l;//shOrders.getAmount();
        	if(amountStr!=null&&StringUtils.isNotBlank(amountStr)){
        		double amount_d = (Double.valueOf(amountStr).doubleValue())*100;//转为分
        		amount = (long)amount_d;
        	}
        	shOrders.setAmount(amount);
        	shOrders.setName("洗衣服务"+shOrders.getId());//订单名称   先写死  洗衣服务+订单号
            xiyiOrderService.add(shOrders);
            return Result.success("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure("添加洗衣订单失败！");
        }
    }

    /**
     * 跳转到编辑页面
     * @param req
     * @param id
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(HttpServletRequest req, Long id) {
    	Long residenceId = UserHolder.getCurrentResidenceId();
    	req.setAttribute("residenceId", residenceId);
    	ShOrders shOrders = xiyiOrderService.queryShOrdersById(id);
        req.setAttribute("shOrders", shOrders);
        //得到用户信息
        ShHistoryAccount shHistoryAccount = historyAccountService.queryShHistoryAccountById(shOrders.getSrcAccountId());
        req.setAttribute("shHistoryAccount", shHistoryAccount);
        return "/kuaidiXiyi/xiyiServerEdit";
    }

    /***
     * 修改
     * @param ShOrders
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Result edit(ShOrders shOrders) {
        try {
        	String phone = shOrders.getKhMobile();		//手机号码
        	String kh_name = shOrders.getKhName();	//手机号码
        	if(StringUtils.isBlank(phone)){
        		 return Result.failure("请输入手机号码！");
        	}
        	if(shOrders.getStatus()==null){
        		return Result.failure("请选择【订单状态】");
        	}
        	//通过手机号码查询用户是否存在
        	Long srcAccountId =shOrders.getSrcAccountId();
        	ShHistoryAccount shHistoryAccount = new ShHistoryAccount();
        	shHistoryAccount.setMobile(phone);
        	List<ShHistoryAccount> list = historyAccountService.queryShHistoryAccountList(shHistoryAccount);
        	if(list!=null && list.size()>0){
        		srcAccountId=list.get(0).getId();
        	}else{									//新增
        		if(StringUtils.isNotBlank(kh_name)){
        			shHistoryAccount.setName(kh_name);
        		}
        		shHistoryAccount.setStatus(1);				//是否可用,1可用,2不可用
        		shHistoryAccount.setGmtCreate(new Date());	//创建时间
        		historyAccountService.add(shHistoryAccount);
        		//再查一边，得到id
        		List<ShHistoryAccount> list2 = historyAccountService.queryShHistoryAccountList(shHistoryAccount);
            	if(list2!=null && list2.size()>0){
            		srcAccountId=list2.get(0).getId();
            	}
        	}
        	shOrders.setSrcAccountId(srcAccountId);
        	shOrders.setGmtModify(new Date());
        	shOrders.setHandler(UserHolder.getUser().getEmployeeName());//添加经办人 cyj
            xiyiOrderService.edit(shOrders);
            return Result.success("修改洗衣订单成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure("修改洗衣订单出现异常！");
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/deleteOrder")
    @ResponseBody
    public Result deleteOrder(String id) {
    	if(StringUtils.isBlank(id)){
    		return Result.failure("无法得到要删除的订单ID！");
    	}
    	ShOrders shOrders = xiyiOrderService.queryShOrdersById(Long.valueOf(id));
    	shOrders.setStatus(4);//代洗衣物：1待处理、5已取件、7已送洗、8待取、2完成、3关闭、4删除
        xiyiOrderService.edit(shOrders);
        return Result.success("删除成功！");
    }

    /**
     * 订单通知
     * @param id
     * @return
     */
    @RequestMapping("/orderNotice")
    @ResponseBody
    public Result orderNotice(Long id) {
    	try {
    		ShOrders shOrders = xiyiOrderService.queryShOrdersById(id);
        	Long residenceId = UserHolder.getCurrentResidenceId();
        	xiyiOrderService.getTaskMessage(residenceId);
        	
        	//得到洗衣店信息
        	ShCompanyLaundry companyLaundry =companyLaundryService.getById(shOrders.getCompanyId());
        	if(companyLaundry!=null){
        		//发送短信通知
        		MessageUtil.sendTimelyForTemplet(SmsTypeEnum.GET_WASH_CODE,UserHolder.getCurrentResidenceId(),
        				shOrders.getSrcMobile(),shOrders.getId(),shOrders.getWishNum(),companyLaundry.getAddr(),companyLaundry.getName());
        	}
            return Result.success("取件提醒成功！");
		} catch (Exception e) {
			e.printStackTrace();
			 return Result.failure("[取件提醒]出现异常！");
		}
    	
    }
    
    /**
     * 导出--洗衣订单
     * @param request
     * @param shOrders
     * @return
     */
    @RequestMapping(value = "/exportXiyiOrder", method = { RequestMethod.GET })
    public void exportXiyiOrder(HttpServletRequest request, ShOrders shOrders, HttpServletResponse response) {
    	//ShOrders shOrders = xiyiOrderService.queryShOrdersById(id);
    	if(!UserHolder.isSuperResidence()){
    		Long residenceId = UserHolder.getCurrentResidenceId();
        	shOrders.setResidenceId(residenceId);
    	}
    	
    	try {
    		DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		shOrders.setOrderType(3); // 订单类型,1收快递,2发快递,3洗衣
    		List<ShOrders> list = xiyiOrderService.queryShOrdersList(shOrders);
    		 String title = "洗衣订单导出";
             List<String> headerNames = new ArrayList<String>();
             headerNames.add("订单号");
             headerNames.add("洗衣公司名称");
             headerNames.add("洗衣面单");
             headerNames.add("客户名称");
             headerNames.add("客户电话");
             headerNames.add("客户地址");
             headerNames.add("代洗时间");
             List<String> cellNames = new ArrayList<String>();
             cellNames.add("id");
             cellNames.add("companyName");//洗衣公司名称
             cellNames.add("outBizNum");//洗衣面单
             cellNames.add("khName");//客户名称
             cellNames.add("srcMobile");//客户电话
             cellNames.add("srcAreaDetail");//客户地址
             cellNames.add("gmtCreate");//代洗时间
             List<Object> datas = new ArrayList<Object>();
             if(list!=null && list.size()>0){
            	 for(int i=0;i<list.size();i++){
            		 ShOrders order = list.get(i);//new ShOrders();
                     order.setId(order.getId());
                     order.setCompanyName(order.getCompanyName());		//洗衣公司名称
                     order.setOutBizNum(order.getOutBizNum());	//洗衣面单
                     order.setKhName(order.getSrcAccountName());			//客户名称
                     order.setSrcMobile(order.getSrcMobile());		//客户电话
                     order.setSrcAreaDetail(order.getDesAreaDetail());	//客户地址
                     order.setGmtCreate(order.getGmtCreate());	//代洗时间
                     datas.add(order);
            	 }
             }
             new ReportExportService().doExportAndDownload(title, headerNames, cellNames, datas, response);
		} catch (Exception e) {
			e.printStackTrace(); 
		}
    }
    
    

}